﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http.Filters;

namespace LeHouse.Server.WebApi.Common
{
    public class TokenAttribute : ActionFilterAttribute
    {
        //http://blog.zhishile.com/Article/Show/5df2a392-8a8c-4e12-8a05-774f47a4570a
        public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            //base.OnActionExecuting(actionContext);

            IEnumerable<string> tokens;
            var existToken = actionContext.Request.Headers.TryGetValues("token", out tokens);
            if (existToken)
            {
                var token = tokens.GetEnumerator();
                if (token.MoveNext())
                {
                    //解析token，校验是否失效
                    var secretKey = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk";
                    try
                    {
                        var jsonPayload = JWT.JsonWebToken.DecodeToObject<Dictionary<string, object>>(token.Current.ToString(), secretKey);

                    }
                    catch (JWT.SignatureVerificationException sve)
                    {
                        var m = sve.Message;
                        //失效：禁止请求 403
                        actionContext.Response = new HttpResponseMessage
                        {
                            StatusCode = System.Net.HttpStatusCode.Forbidden,
                            Content = new StringContent("非法请求,用户身份无效", Encoding.UTF8),
                            ReasonPhrase = "403",
                        };
                    }
                    catch (JWT.TokenExpiredException ex)
                    {
                        var m = ex.Message;
                        //失效：禁止请求 404
                        actionContext.Response = new HttpResponseMessage
                        {
                            StatusCode = System.Net.HttpStatusCode.Forbidden,
                            Content = new StringContent("非法请求,用户令牌已过期，请重新登录", Encoding.UTF8),
                            ReasonPhrase = "404",
                        };
                    }
                    catch (ArgumentException ae)
                    {
                        var m = ae.Message;
                        //参数错误
                        actionContext.Response = new HttpResponseMessage
                        {
                            StatusCode = System.Net.HttpStatusCode.Forbidden,
                            Content = new StringContent("非法请求,参数提交有误", Encoding.UTF8),
                            ReasonPhrase = "405"
                        };
                    }
                    catch (Exception ex)
                    {
                        var m = ex.Message;
                        //其他异常 服务器错误：500
                        actionContext.Response = new HttpResponseMessage
                        {
                            StatusCode = System.Net.HttpStatusCode.InternalServerError,
                            Content = new StringContent("服务器发生异常", Encoding.UTF8),
                            ReasonPhrase = "500",
                        };
                    }
                }
            }
            else
            {
                //指定公开访问的方法
                List<string> LsactionName = new List<string>();
                LsactionName.Add("GetCodeImg");
                LsactionName.Add("GetLogin");
                var v = actionContext.Request.Properties.First(t => t.Key == "MS_HttpActionDescriptor");
                System.Web.Http.Controllers.ReflectedHttpActionDescriptor
                    value = (System.Web.Http.Controllers.ReflectedHttpActionDescriptor)v.Value;
                if (!LsactionName.Contains(value.ActionName))
                {
                    //没有token，也不是指定公开访问的方法 拒绝访问
                    actionContext.Response = new HttpResponseMessage
                    {
                        StatusCode = System.Net.HttpStatusCode.Unauthorized,
                        Content = new StringContent("服务器拒绝访问，要求身份验证", Encoding.UTF8),
                        ReasonPhrase = "401"
                    };
                }
            }
        }
    }
}